import {
  POPULAR_REFRESH,
  POPULAR_REFRESH_SUCCESS,
  POPULAR_REFRESH_FAIL,
  POPULAR_LOAD_MORE_SUCCESS,
  POPULAR_LOAD_MORE_FAIL
} from '../types';
import DataStore,{FLAG_STORAGE} from "../../expand/offlineCache/DataStore";
import handleData from "./actionCommen/actionUtil";

// 获取数据
export function onLoadPopularData(storeName, url, pageSize) {
  return dispatch => {
    // 刷新
    dispatch({type: POPULAR_REFRESH, storeName: storeName});

    // 实例化DataStore，获取数据
    let dataStore = new DataStore();
    dataStore.fetchData(url,FLAG_STORAGE.flag_popular)
      .then(data => {   // 下拉刷新成功
        handleData(POPULAR_REFRESH_SUCCESS,dispatch,data,pageSize,storeName);
      })
      .catch(error => {   // 下拉刷新失败
        console.log(error);
        dispatch({
          type: POPULAR_REFRESH_FAIL,
          error,
          storeName,
        })
      })
  }
}

// 上拉加载更多
export function onLoadMorePopular(storeName, pageIndex, pageSize, dataArray = [], callBack) {
  return dispatch => {
    // 模拟网络请求，延迟500毫秒
    setTimeout(() => {
      // 如果超过总数，执行callBack
      if ((pageIndex - 1) * pageSize >= dataArray.length) {
        if (typeof callBack === 'function') {
          callBack('no more')
        }
        // 上拉刷新失败
        dispatch({
          type: POPULAR_LOAD_MORE_FAIL,
          error: 'no more',
          storeName,
          pageIndex: --pageIndex,
          projectModes: dataArray
        })
      } else {  // 没有超过总数
        // 本次和载入的最大数据
        let max = pageSize * pageIndex > dataArray.length ? dataArray.length : pageSize * pageIndex;
        // 上拉刷新成功
        dispatch({
          type: POPULAR_LOAD_MORE_SUCCESS,
          storeName,
          pageIndex,
          projectModes: dataArray.slice(0, max)
        })
      }
    }, 500)
  }
}

